<template>
  <div v-if="!isHidden">
    <el-sub-menu
      v-if="hasMorethanOneChildren(menu as any) || (hasOneChildren(menu as any) && isAlwaysShow(menu as any))"
      :index="resolvePath($props.menu.menuUrl)"
      teleported
    >
      <template v-slot:title>
        <el-icon v-if="menu.menuIcon">
          <component :is="menu.menuIcon"></component>
        </el-icon>
        <!--        <i v-if="menu.menuIcon" :class="menu.menuIcon"></i>-->
        <span>{{ menu.menuName }}</span>
      </template>
      <template v-for="menuC in menu.children" :key="menuC.menuId">
        <DMenu :menu="menuC" :base-path="resolvePath(menuC.menuUrl)"></DMenu>
      </template>
    </el-sub-menu>
    <DMenuLink v-else-if="hasOneChildren(menu as any)" :to="resolvePath(menu.children[0].menuUrl)">
      <el-menu-item :index="resolvePath(menu.children[0].menuUrl)">
        <i v-if="menu.children[0].menuIcon" :class="menu.children[0].menuIcon"></i>
        <template v-slot:title>
          <span>{{ menu.children[0].menuName }}</span>
        </template>
      </el-menu-item>
    </DMenuLink>
    <DMenuLink v-else :to="$props.basePath">
      <el-menu-item :index="$props.basePath">
        <i v-if="menu.menuIcon" :class="menu.menuIcon"></i>
        <template v-slot:title>
          <span>{{ menu.menuName }}</span>
        </template>
      </el-menu-item>
    </DMenuLink>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue';
import { isTrue, SysMenu } from 'pf-component';
import path from 'path';
import DMenuLink from '@/components/DMenuLink.vue';

export default defineComponent({
  name: 'DMenu',
  components: { DMenuLink },
  props: {
    menu: {
      type: Object,
      default: () => {
        return {};
      }
    } as any,
    basePath: {
      type: String,
      default: ''
    }
  },
  setup(prop, { emit }) {
    const resolvePath = (menuUrl: string) => {
      let routePath: string = menuUrl;
      // if (isExternal(routePath)) {
      //   return routePath
      // }
      // if (isExternal(prop.basePath)) {
      //   return prop.basePath
      // }
      const _path = path.resolve(
        prop.basePath.startsWith('/') ? prop.basePath : `/${prop.basePath}`,
        routePath
      );
      return _path;
    };
    const hasMorethanOneChildren = (menu: SysMenu): boolean => {
      return !!(menu.children && menu.children.length && menu.children.length > 1);
    };
    const hasOneChildren = (menu: SysMenu): boolean => {
      return !!(menu.children && menu.children.length && menu.children.length === 1);
    };
    const isAlwaysShow = (menu: SysMenu): boolean => {
      return isTrue(menu.alwaysShow);
    };
    const isHidden = computed(() => {
      return isTrue(prop.menu.hidden);
    });
    return {
      resolvePath,
      hasMorethanOneChildren,
      hasOneChildren,
      isAlwaysShow,
      isHidden
    };
  }
});
</script>

<style scoped></style>
